import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'global.dart';
import '../../common/extentsion/localStorageExample.dart';

class DioClient {
  static final DioClient _instance = DioClient._internal();

  factory DioClient() {
    return _instance;
  }

  DioClient._internal() {
    _init();
  }

  late Dio dio;

  Future<void> _init() async {
    dio = Dio();
    // 设置超时时间
    dio.options.connectTimeout = const Duration(seconds: 10);
    dio.options.receiveTimeout = const Duration(seconds: 10);
  }

  Future<Map<String, dynamic>> get(
    String url, {
    Map<String, dynamic>? queryParameters,
    bool showLoading = true,
  }) async {
    try {
      showLoadingIfNeeded(showLoading);
      queryParameters = {"token": await LocalStorageExample.getString("token")};
      var response = await dio.get(
        url,
        queryParameters: queryParameters,
      );
      dismissLoadingIfNeeded(showLoading);
      if (response.data['data'] is Map) {
        return response.data['data'];
      }
      return {};
    } catch (e) {
      dismissLoadingIfNeeded(showLoading);
      rethrow;
    }
  }

  Future<Map<String, dynamic>> post(
    String url, {
    Map<String, dynamic>? data,
    Map<String, dynamic>? queryParameters,
    bool showLoading = true,
  }) async {
    try {
      showLoadingIfNeeded(showLoading);
      Map<String, dynamic>? token = {"token": await LocalStorageExample.getString("token")};
      Map<String, dynamic> params = {...token,...?queryParameters};
      var response = await dio.post(
        url,
        queryParameters: params,
      );
      dismissLoadingIfNeeded(showLoading);
      if (response.data['data'] is Map) {
        return response.data['data'];
      } else {
        EasyLoading.showToast(response.data['message']);
      }
      return {};
    } catch (e) {
      dismissLoadingIfNeeded(showLoading);
      rethrow;
    }
  }
}
